<template>
  <a-modal
    :title="title"
    :width="900"
    :visible="visible"
    :confirm-loading="loading"
    @cancel="this.handelCancel"
    cancelText="取消"
    okText="保存"
    :destroyOnClose="true"
    :footer="null"
  >
    <div class="steps-content">
      <div v-if="current === 0">
        <a-upload-dragger
          name="file"
          :file-list="fileList"
          :multiple="false"
          @change="handleChange"
          accept=".xls,.xlsx"
          :before-upload="beforeUpload"
          :showUploadList="true"
          :remove="handleRemove"
          :disabled="disabled"
          @reject="handleReject"
        >
          <p class="ant-upload-drag-icon">
            <a-icon type="inbox" />
          </p>
          <p class="ant-upload-text">
           点击或拖拽文件到此处上传
          </p>
          <p class="ant-upload-hint">
            支持100MB以内的xls、xlsx文件，内容在20000行和200列以内,只支持单个文件上传
          </p>
        </a-upload-dragger>
      </div>

      <div v-if="current === 1">
        <div class="flexRow bold alignLeft bottom10">
          <a-tabs
            tab-position="left"
            @change="pageChange"
          >
            <a-tab-pane v-for="list in fileInfo"
             :key="list.sheetNumber"
             :tab="list.sheetName"
            >
            <div class="import-inner">
              <span>选择表头：</span>
              <span>第<a-input-number size="small" :min="1" :max="10" style="width: 50px;" v-model="headerRowNumber"/>行</span>
            </div>
            <a-table :columns="columns"
                :data-source="tableData" size="small"
                :pagination='false'
              />
              <!-- <table border="1">
                <tr v-for="row in list.rows"
                  :key='row.rowNumber'
                >
                  <td v-for="cell in row.cells"
                    style="width: 100px"
                    :key='cell.columnNumber'>
                    {{cell.value}}
                  </td>
                </tr>
              </table> -->
            </a-tab-pane>
          </a-tabs>
        </div>
      </div>

      <div v-if="current === 2">
        <div class="flexRow bold alignLeft bottom10">
          <div class="flex">
              工作表字段
          </div>
          <div class="controlSeparate"></div>
          <div class="flex">
              Excel 列
          </div>
        </div>
        <a-form :form="form">
          <a-form-item class="bottom0" v-for="item in fields" :key="item.name">
            <a-form-item
              class="bottom0"
              :style="{ display: 'inline-block', width: 'calc(50% - 50px)' }"
            >
              <a-input
                :defaultValue="item.alia"
                :disabled="true"
                style="color: #767676"
              />
            </a-form-item>
            <span :style="{ display: 'inline-block', width: '100px', textAlign: 'center' }">
            </span>
            <a-form-item
              class="bottom0"
              :style="{ display: 'inline-block', width: 'calc(50% - 50px)' }">
              <a-select v-decorator="[item.name, {initialValue: matchingField(item.alia)}]">
                <a-select-option value="">
                  请选择
                </a-select-option>
                <a-select-option :value="cell.columnNumber" v-for="cell in header" :key="cell.columnNumber">
                  {{ cell.value }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-form-item>
        </a-form>
      </div>
    </div>
    <div class="steps-action">
      <a-button v-if="current > 1" @click="prev">
        上一步
      </a-button>
      <a-button v-if="current < steps.length - 1 && uploadState" style="margin-left: 8px" type="primary" @click="next">
        下一步
      </a-button>
      <a-button
        v-if="current === steps.length - 1"
        type="primary"
        style="margin-left: 8px"
        @click="handleImport"
      >
        开始导入
      </a-button>
    </div>

    <!--取消导入 对话框-->
    <a-modal
      :visible="false"
      @cancel="this.handelCancel"
      :destroyOnClose="true"
    >
    </a-modal>

  </a-modal>
</template>

<script>
  import {
    uploadExcel,
    previewExcel,
    } from "@/api/worksheet";
  import to from 'await-to-js'
  export default {
    name: 'ImportExcelData',
    props: {
      visible: {
        type: Boolean,
        required: true
      },
      loading: {
        type: Boolean,
        default: () => false
      },
      fields: {
        type: Array,
        default: () => []
      }
    },
    data () {
      return {
        form: this.$form.createForm(this),
        sheetNumber: 0,
        headerRowNumber: 1,
        filePath: '',
        fileInfo: [],
        tableData: [],
        columns: [],
        uploadState: false,
        disabled: false,
        fileList: [],
        current: 0,
        steps: [
          {
            title: '上传 Excel',
            content: 'First-content',
          },
          {
            title: '选择内容',
            content: 'middle-content',
          },
          {
            title: '字段映射',
            content: 'Last-content',
          },
        ],
      };
    },
    computed: {
      title: function () {
        return `数据导入 - ${ this.steps[this.current].title } （${ this.current + 1 }/${ this.steps.length }）`
      },
      header(){
        console.log(this.fileInfo[this.sheetNumber]?.rows[this.headerRowNumber - 1].cells || []);
        return this.fileInfo[this.sheetNumber]?.rows[this.headerRowNumber - 1].cells || []
      }
    },
    methods: {
      matchingField(alia){
        let h = this.header.find(f => f.value === alia)
        if(!h) return null
        return h.columnNumber
      },
      next () {
        if (this.fileList.length === 0) {
          this.$message.warn("请先选择一个文件")
          return
        }

        this.current++;
        if (this.current === 1) {
          this.handlePreviewExcel()
        }
      },
      prev () {
        this.current--;
      },
      pageChange (value) {
        this.sheetNumber = value
        this.initTableData(value)
      },
      handelCancel () {
        this.backToDefaultValue()

        this.$emit('cancel')
      },
      handleChange (info) {
        /*let fileList = [...info.fileList]
        fileList = fileList.splice(-1)

        const file = fileList[0]
        this.checkFile(file, fileList)*/
      },
      checkFile (file, fileList) {
        if (file) {
          const isJpgOrPng = file.name.endsWith(".xls") || file.name.endsWith(".xlsx")
          if (!isJpgOrPng) {
            this.$message.error('You can only upload XLS or XLSX file!');
          }
          const isLt2M = file.size / 1024 / 1024 < 100;
          if (!isLt2M) {
            this.$message.error('文件必须小于 100MB!');
          }

          if (!isJpgOrPng || !isLt2M) {
            this.fileList = []
            return false
          }

          this.fileList = fileList

          return true
        }
      },
      handleReject (fileList) {
        this.$message.warn("文件格式不符合")
      },
      beforeUpload (file, fileList) {
        const checkResult = this.checkFile(file, fileList)
        // 上传文件
        checkResult && this.handleUpload()
        return false
      },
      handleRemove (file) {
        this.fileList = []
      },
      async handleUpload () {
        const file = this.fileList[0]
        const formData = new FormData()
        formData.append("file", file)
        const loading = this.$loading({
          lock: true,
          text: '正在上传数据，请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        let [err, data] = await to(uploadExcel(formData))
        loading.close()
        if (err) {
          this.$message.error("上传失败")
          return
        }
        this.$message.success(`${file.name} 上传成功`)
        this.uploadState = true
        this.filePath = data.url
      },
      async handlePreviewExcel () {
        if (this.filePath === '') {
          return
        }
        const param = {
          filePath: this.filePath
        }
        const loading = this.$loading({
          lock: true,
          text: '正在请求数据，请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        let [err, data] = await to(previewExcel(param))
        loading.close()
        if (err) {
          this.$message.error("预览失败")
          return
        }
        this.fileInfo = data
        this.initTableData(0)
      },
      initTableData(index){
        let tableHeader = this.fileInfo[index]?.rows[0]?.cells || []
        let columns = tableHeader.map(t => ({
          title: t.value,
          dataIndex: t.value,
        }))
        this.columns = [{
          title: 1,
          dataIndex: 'sort_index',
        },...columns]
        let tableData = []
        for(let i = 1; i < this.fileInfo[index]?.rows.length; i++){
          let obj = {
            key: i,
            sort_index: i + 1
          }
          for (let j = 0; j < tableHeader.length; j++) {
            obj[tableHeader[j].value] = this.fileInfo[index]?.rows[i]?.cells[j]?.value || ""
          }
          tableData.push(obj)
        }
        this.tableData = tableData
      },
      handleImport () {
        this.$emit('ok', {
          sheetNumber: this.sheetNumber,
          rowNumber: this.headerRowNumber - 1,
          filePath: this.filePath
        })

        this.backToDefaultValue()
      },
      backToDefaultValue () {
        this.current = 0
        this.fileList = []
        this.uploadState = false
        this.filePath = ''
      }
    }
  }
</script>

<style lang="less" scoped>
  @import "./importExcel.less";
  .steps-content {
    border-radius: 6px;
    min-height: 300px;
    text-align: center;
  }

  .steps-action {
    margin-top: 24px;
    text-align: right;
  }
</style>

<style lang="less">
  .import-inner, .bottom0{
    input {
      color: black !important
    }
  }
</style>
